﻿using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace CuteRibs.WowArmory.Models
{
	public class BNDateTimeConverter : DateTimeConverterBase
	{
		private static readonly DateTime StartDateTime = new DateTime(1970, 1, 1);

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			object value = reader.Value;

			if (value is Array)
			{
				return (value as Array).Cast<long>().Select(v => ConvertToDate(v)).ToArray();
			}
			else
			{
				return ConvertToDate(Convert.ToInt64(reader.Value));
			}
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			if (value is DateTime)
			{
				writer.WriteValue(ConvertToMilliseconds((DateTime)value));
			}
			else if (value is DateTime[])
			{
				writer.WriteStartArray();

				foreach (var v in (value as DateTime[]))
				{
					writer.WriteValue(ConvertToMilliseconds(v));
				}

				writer.WriteEndArray();
			}
			else
			{
				throw new Exception("Expected date or date array object.");
			}
		}

		public static long ConvertToMilliseconds(DateTime dateTime)
		{
			return Convert.ToInt64((dateTime.ToUniversalTime() - StartDateTime).TotalMilliseconds);
		}

		public static DateTime ConvertToDate(long seconds)
		{
			return StartDateTime.AddMilliseconds(seconds).ToLocalTime();
		}
	}
}
